﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UL360DataNET40;
using System.Web.Script.Serialization;
using UL360Admin.Survey.Models;
using UL360Admin.Survey.Utils;
using UL360SurveyCommon;
using System.Text.RegularExpressions;

namespace UL360Admin.Survey
{
    public partial class requestHandler : System.Web.UI.Page
    {
        string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

        protected void Page_Load(object sender, EventArgs e)
        {
            //New instance of javascriptserializer for deserializing json request
            JavaScriptSerializer js = new JavaScriptSerializer();

            try
            {
                //If request is for saving the form
                if (Request.QueryString["SaveForm"] != null && Request.QueryString["FormType"] != null)
                {
                    //Declare variables for reading request inputstream to get JSON-string
                    Stream body = Request.InputStream;
                    Encoding encoding = Request.ContentEncoding;
                    StreamReader reader = new StreamReader(body, encoding);

                    //Read stream to end
                    string jsonRequest = reader.ReadToEnd();

                    //Deserialize JSON request
                    SaveFormRequest req = js.Deserialize<SaveFormRequest>(jsonRequest);

                    //Save data to database
                    SaveFormResponse result = SurveyFormUtil.SaveForm(req);

                    //Send response
                    Response.Clear();
                    Response.ContentType = "text/json";
                    Response.Write(js.Serialize(result));
                }
                else if (Request.QueryString["ShowReport"] != null && Request.QueryString["FormType"] != null && Request.QueryString["CourseId"] != null)
                {
                    //Parse querystring values to int
                    int formType, courseId;
                    bool sendmail = false;
                    int.TryParse(Request.QueryString["FormType"], out formType);
                    int.TryParse(Request.QueryString["CourseId"], out courseId);
                    if (Request.QueryString["SendMail"] != null)
                    {
                        sendmail = true;
                    }

                    //Save data to database
                    ReportResponse report = ReportsUtil.CreateReport(formType, courseId, sendmail);


                    if (sendmail == true)
                    {
                        string path = Server.MapPath("~/Survey/MailTemplates/ReportMail.xml");
                        List<MailTemplate> templates = UL360Admin.Survey.Utils.Templating.
                        LoadTemplate(path);

                        //Send report to tutors
                        MailReportResponse mailReport = ReportsUtil.MailReport(report.ReportContent, templates, courseId);

                        //Send response
                        Response.Clear();
                        Response.ContentType = "text/json";
                        Response.Write(js.Serialize(mailReport));
                    }
                    else
                    {
                        //Send response
                        Response.Clear();
                        Response.ContentType = "text/json";
                        Response.Write(js.Serialize(report));
                    }
                }
            }
            //If error occured
            catch(Exception exc)
            {
                //Log error
                string errorTicket = LoggerCommon.LogNewEntry(
                    new LoggerCommon.LogNewEntryDelegate(Logger.LogNewEntry),
                    MethodName, exc.ToString(), (int)SurveyLoggingLevel.Error);

                //Send response
                Response.Clear();
                Response.ContentType = "text/json";
                Response.Write(js.Serialize(new ExceptionResponse(errorTicket)));
            }
        }
    }
}